<html xmlns:th="http://www.thymeleaf.org" lang="zh">
<head th:replace="components/layout :: head(~{:: title}, ~{:: link}, ~{:: script}, ~{:: style})">
    <title>首页</title>
    <link rel="stylesheet" th:href="@{/css/my/demo1.css}">
    <link rel="stylesheet" th:href="@{/css/my/demo2.css}">
    <script type="text/javascript" th:src="@{/js/my/demo1.js}"></script>
    <script type="text/javascript" th:src="@{/js/my/demo2.js}"></script>
    <style rel="stylesheet">
        #con {
            background: #3c763d;
        }
    </style>
    <script type="text/javascript">
        var websocket = null;

        $(function() {
            createWebscoket();
        });

        function createWebscoket() {
            var sid = $('#sid').val();
            console.log('sid', sid);
            //判断当前浏览器是否支持WebSocket
            if ('WebSocket' in window) {
                websocket = new WebSocket('ws://127.0.0.1:8080/websocket/' + sid);//此处地址在分情况测试的时候需要修改
            } else {
                alert('Not support websocket');
            }

            //发生错误时
            websocket.onerror = function() {
                setMessageInnerHTML('error');
            };

            //成功建立连接时
            websocket.onopen = function(event) {
                //setMessageInnerHTML("open");
            };

            //接收到消息时
            websocket.onmessage = function(event) {
                setMessageInnerHTML(event.data);
            };

            //关闭连接时
            websocket.onclose = function() {
                setMessageInnerHTML('close');
            };

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function() {
                websocket.close();
            };
        }


        //显示服务器端返回的消息
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }

        //关闭连接按钮
        function close() {
            websocket.close();
        }

        //发送消息按钮
        function send() {
            var message = document.getElementById('text').value;
            websocket.send(message);
        }
    </script>
</head>
<body>
<div class="container" style="margin-top: 10em">
    <input type="text" id="sid" name="sid" th:value="${sid}">
    <br>
    <label for="text">
        <input id="text" type="text"/>
    </label>
    <button onclick="send()">Send</button>
    <button onclick="close()">Close</button>
    <div id="message"></div>
</div>
</body>

</html>
